import { Form, Input, Button } from "antd";
import { message } from "../../utils/customMessage";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { http } from "../../utils/request";
import type { LoginParams, MenuItem } from "../../services/api";
import { API_ENDPOINTS } from "../../services/api";
import "./index.scss";

const Login = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 转换菜单数据
  const convertMenu = (menu: any): MenuItem => {
    const menuItem: MenuItem = {
      id: menu.id,
      title: menu.menuName,
      path: menu.url || `/${menu.menuName.toLowerCase().replace(/\s+/g, "-")}`,
      component: menu.component || "",
    };

    if (menu.menuList && menu.menuList.length > 0) {
      menuItem.children = menu.menuList.map(convertMenu);
    }

    return menuItem;
  };

  const handleLogin = async (values: LoginParams) => {
    try {
      setLoading(true);

      const result = await http.post("/api/user/login", values);

      if (+result.status === 200 && result.data) {
        const userData = result.data;

        // 存储必要的关键信息
        localStorage.setItem("token", userData.token);
        localStorage.setItem("userId", userData.id.toString());
        localStorage.setItem("roleId", userData.role.id.toString());

        message.success("登录成功");

        // 直接跳转到首页，确保能够进入
        navigate("/home", { replace: true });
      } else {
        message.error(result.message || "登录失败");
      }
    } catch (error) {
      message.error("登录失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-form-wrapper">
        <div className="login-title">电网数据管理系统</div>
        <Form
          form={form}
          className="login-form"
          onFinish={handleLogin}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input
              placeholder="用户名"
              prefix={<UserOutlined />}
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password
              placeholder="密码"
              prefix={<LockOutlined />}
              size="large"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              loading={loading}
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
